import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
  Req,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';

import { storage } from './my-file-storage';
import { FileInterceptor } from '@nestjs/platform-express';
import path, { normalize } from 'node:path';
import { Book } from './entities/book.entity';

@Controller('book')
export class BookController {
  constructor(private readonly bookService: BookService) {}

  @Post('create')
  create(@Body() createBookDto: CreateBookDto) {
    return this.bookService.create(createBookDto);
  }

  @Get('list')
  async list(@Query('name') name: string): Promise<Book[]> {
    const books = await this.bookService.list(name);
    return books;
  }

  // Express 不会自动重排序路由。它只是按你定义的顺序注册。如果这个路由在 @Get('list')路由之前注册，
  // 那么它将会 匹配到/book/list路由，导致想要匹配的@Get('list') 路由匹配不到。
  @Get(':id')
  async findById(@Param('id') id: string) {
    return this.bookService.findById(+id);
  }

  @Put('update')
  async update(@Body() updateBookDto: UpdateBookDto) {
    return this.bookService.update(updateBookDto);
  }

  @Delete('delete/:id')
  async delete(@Param('id') id: string) {
    return this.bookService.delete(+id);
  }

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: storage,
      limits: {
        fileSize: 1024 * 1024 * 30, // 30MB
      },
      fileFilter(req, file, callback) {
        const extname = path.extname(file.originalname);
        if (['.png', '.jpg', '.gif'].includes(extname)) {
          callback(null, true);
        } else {
          callback(new BadRequestException('文件类型不支持,请上传图片'), false);
        }
      },
    }),
  )
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Req() req: Request,
  ) {
    if (!file) {
      throw new BadRequestException('文件上传失败');
    }
    const protocol = (req as any).protocol;
    const host = (req as any).get('host');
    const url = normalize(`${protocol}://${host}/${file.path}`)
      .split(path.sep)
      .join('/');
    return {
      url,
      filename: file.filename,
    };
  }
}
